﻿using ModbusDataParseTool.Entity;
using ModbusDataParseTool.Model;
using ModbusDataParseTool.Service;
using ModbusDataParseTool.Utility;
using MyUtility.Utility;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace ModbusDataParseTool.VIewModel
{
    public class MainWindowViewModel : ViewModelBase
    {
        #region ViewModel

        private string inputStrData;

        public string InputStrData
        {
            get { return inputStrData; }
            set 
            {
                inputStrData = value;
                RaisePropertyChanged("InputStrData");
            }
        }

        private string outputStrData;

        public string OutputStrData
        {
            get { return outputStrData; }
            set
            {
                outputStrData = value;
                RaisePropertyChanged("OutputStrData");
            }
        }

        private ObservableCollection<BaseInfoCfgEntity> baseInfoCfgEnts = new ObservableCollection<BaseInfoCfgEntity>();

        public ObservableCollection<BaseInfoCfgEntity> BaseInfoCfgEnts
        {
            get { return baseInfoCfgEnts; }
            set
            {
                baseInfoCfgEnts = value;
                RaisePropertyChanged("BaseInfoCfgEnts");
            }
        }

        private int selectProtocolIndex;

        public int SelectProtocolIndex
        {
            get { return selectProtocolIndex; }
            set
            {
                selectProtocolIndex = value;
                RaisePropertyChanged("SelectProtocolIndex");
            }
        }

        #endregion


        #region Service
        private ParseDataService parseDataService = SingletonProvider<ParseDataService>.Instance;

        #endregion

        #region Model
        private ProtocolModel protocolModel = SingletonProvider<ProtocolModel>.Instance;

        #endregion

        public MainWindowViewModel()
        {
            baseInfoCfgEnts = new ObservableCollection<BaseInfoCfgEntity>(protocolModel.BaseInfoCfgEnts);
        }


        public void ParseData()
        {
            if (string.IsNullOrEmpty(InputStrData))
            {
                return;
            }
            //临时，获取第一个协议
            BaseInfoCfgEntity baseInfoCfgEnt = baseInfoCfgEnts[SelectProtocolIndex];
            ModbusProtocolEntity modbusProtocolEntity = protocolModel.ProtocalKeyValuePairs[baseInfoCfgEnt.ProtocolCode];

            if (parseDataService.ParseDataByUnit(InputStrData, modbusProtocolEntity, out string endParseDataStr))
            {
                OutputStrData = endParseDataStr;
            }
        }

    }
}
